﻿using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stardance.ProgramTimer
{
    public class RecordJob : IJob
    {
        private readonly string iniPath = AppDomain.CurrentDomain.BaseDirectory + "settings.ini";

        private static RecordJob _job;

        public static RecordJob Instance
        {
            get
            {
                if(_job == null)
                {
                    _job = new RecordJob();
                }
                return _job;
            }
        }

        private RecordJob()
        {

        }

        public Task Execute(IJobExecutionContext context)
        {
            return Task.Factory.StartNew(()=>
            {
                if(!File.Exists("ProgramStatus.json"))
                {
                    Init();
                }
                string rawData = File.ReadAllText("ProgramStatus.json");
                List<ProgramStatus> status = JsonConvert.DeserializeObject<List<ProgramStatus>>(rawData);
                string pros = new IniFile(iniPath).IniReadValue("ProgramNames", "List");
                string[] proArr = pros.Split(',');
                Process[] process = Process.GetProcesses();
                foreach(string s in proArr)
                {
                    if(process.Select(i => i.ProcessName).Contains(s))
                    {
                        status.Where(i => i.Name == s).FirstOrDefault().TimeCount++;
                        status.Where(i => i.Name == s).FirstOrDefault().LastRun = DateTime.Now.ToUniversalTime();
                    }
                }
                string newData = JsonConvert.SerializeObject(status);
                File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "ProgramStatus.json",newData);
            });
        }

        private void Init()
        {
            string pros = new IniFile(iniPath).IniReadValue("ProgramNames", "List");
            string[] proArr = pros.Split(',');
            List<ProgramStatus> status = new List<ProgramStatus>();
            foreach(string s in proArr)
            {
                status.Add(new ProgramStatus
                {
                    Name = s,
                    TimeCount = 0
                });
            }
            string newData = JsonConvert.SerializeObject(status);
            string root = AppDomain.CurrentDomain.BaseDirectory;
            File.WriteAllText(root + "ProgramStatus.json",newData);
        }
    }
}
